<template>
  <div class="discuss-detail-container">
    <div class="back-link">
      <el-button @click="goBack" icon="el-icon-arrow-left" text>返回列表</el-button>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="!discussDetail" class="empty-container">
      <el-empty description="讨论不存在或已被删除"></el-empty>
    </div>
    
    <template v-else>
      <div class="discuss-content-container">
        <div class="discuss-header">
          <h1 class="discuss-title">{{ discussDetail.title }}</h1>
          <div class="discuss-meta">
            <div class="author-info">
              <el-avatar :size="32">{{ discussDetail.username?.charAt(0).toUpperCase() }}</el-avatar>
              <span class="author-name">{{ discussDetail.username }}</span>
            </div>
            <span class="publish-time">{{ formatTime(discussDetail.createtime) }}</span>
          </div>
          <div class="discuss-tags" v-if="discussDetail.tags && discussDetail.tags.length > 0">
            <el-tag v-for="tag in discussDetail.tags" :key="tag" size="small">{{ tag }}</el-tag>
          </div>
        </div>
        
        <div class="discuss-body markdown-body" v-html="renderMarkdown(discussDetail.content)"></div>
        
        <div class="discuss-actions">
          <el-button 
            :type="discussDetail.supported ? 'primary' : 'default'"
            @click="handleSupport"
            :loading="supporting"
          >
            <el-icon><Star /></el-icon>
            {{ discussDetail.supportcount || 0 }} 点赞
          </el-button>
          
          <el-button 
            type="danger" 
            @click="handleDelete" 
            v-if="canDelete"
            :loading="deleteLoading"
          >
            <el-icon><Delete /></el-icon> 删除
          </el-button>
        </div>
      </div>
      
      <div class="comment-container">
        <h2 class="comment-title">评论 ({{ commentList.length }})</h2>
        
        <div class="comment-form" v-if="userStore.isAuthenticated">
          <el-input
            v-model="commentContent"
            type="textarea"
            :rows="3"
            placeholder="写下你的评论..."
            maxlength="500"
            show-word-limit
          ></el-input>
          <div class="form-actions">
            <el-button 
              type="primary" 
              @click="handleAddComment"
              :loading="commenting"
              :disabled="!commentContent.trim()"
            >发表评论</el-button>
          </div>
        </div>
        
        <div v-else class="login-tip">
          <el-link type="primary" @click="goToLogin">登录</el-link> 后参与评论
        </div>
        
        <div class="comment-list">
          <el-empty v-if="commentList.length === 0" description="暂无评论"></el-empty>
          
          <div v-else class="comment-items">
            <div v-for="comment in commentList" :key="comment.cid" class="comment-item">
              <div class="comment-header">
                <div class="commenter-info">
                  <el-avatar :size="24">{{ comment.username?.charAt(0).toUpperCase() }}</el-avatar>
                  <span class="commenter-name">{{ comment.username }}</span>
                </div>
                <span class="comment-time">{{ formatTime(comment.createtime) }}</span>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-actions">
                <el-button 
                  type="text" 
                  @click="handleDeleteComment(comment.cid)"
                  v-if="canDeleteComment(comment)"
                >删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { View, Star, Delete } from '@element-plus/icons-vue';
import { marked } from 'marked';
import { getDiscussDetail, supportDiscuss, deleteDiscuss, addComment, deleteComment } from '../../services/discuss';
import { useUserStore } from '../../stores/user';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const discussDetail = ref<any>(null);
const commentList = ref<any[]>([]);
const commentContent = ref('');
const loading = ref(false);
const supporting = ref(false);
const deleteLoading = ref(false);
const commenting = ref(false);

// 判断是否可以删除讨论
const canDelete = computed(() => {
  return userStore.isAuthenticated && discussDetail.value && discussDetail.value.uid === userStore.uid;
});

// 加载讨论详情
const loadDiscussDetail = async () => {
  const did = Number(route.params.id);
  if (!did) {
    ElMessage.error('讨论ID无效');
    return;
  }
  
  loading.value = true;
  try {
    const res = await getDiscussDetail({ did });
    discussDetail.value = res.data.discuss || null;
    commentList.value = res.data.commentlist || [];
  } catch (error: any) {
    ElMessage.error(error.message || '加载讨论详情失败');
  } finally {
    loading.value = false;
  }
};

// 格式化时间
const formatTime = (timestamp: string) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  // 24小时内
  if (diff < 24 * 60 * 60 * 1000) {
    return '今天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 48小时内
  if (diff < 48 * 60 * 60 * 1000) {
    return '昨天 ' + date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  }
  
  // 其他
  return date.toLocaleDateString('zh-CN');
};

// 渲染Markdown
const renderMarkdown = (content: string) => {
  if (!content) return '';
  return marked(content);
};

// 返回列表
const goBack = () => {
  router.push('/discuss');
};

// 跳转到登录页
const goToLogin = () => {
  router.push('/login');
};

// 点赞讨论
const handleSupport = async () => {
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  supporting.value = true;
  try {
    await supportDiscuss({ did: discussDetail.value.did });
    discussDetail.value.supported = !discussDetail.value.supported;
    discussDetail.value.supportcount = discussDetail.value.supported
      ? (discussDetail.value.supportcount || 0) + 1
      : (discussDetail.value.supportcount || 1) - 1;
  } catch (error: any) {
    ElMessage.error(error.message || '操作失败');
  } finally {
    supporting.value = false;
  }
};

// 删除讨论
const handleDelete = async () => {
  if (!canDelete.value) return;
  
  try {
    await ElMessageBox.confirm('确定要删除该讨论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const did = Number(route.params.id);
    if (!did) return;
    
    deleteLoading.value = true;
    await deleteDiscuss({ did });
    ElMessage.success('删除成功');
    router.push('/discuss');
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败');
    }
  } finally {
    deleteLoading.value = false;
  }
};

// 发表评论
const handleAddComment = async () => {
  if (!userStore.isAuthenticated) {
    ElMessage.warning('请先登录');
    router.push('/login');
    return;
  }
  
  if (!commentContent.value.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }
  
  commenting.value = true;
  try {
    await addComment({
      did: discussDetail.value.did,
      content: commentContent.value.trim()
    });
    
    // 重新加载评论列表
    const res = await getDiscussDetail({ did: discussDetail.value.did });
    commentList.value = res.data.comments || [];
    
    // 清空评论框
    commentContent.value = '';
    ElMessage.success('评论成功');
  } catch (error: any) {
    ElMessage.error(error.message || '评论失败');
  } finally {
    commenting.value = false;
  }
};

// 删除评论
const handleDeleteComment = async (cid: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await deleteComment({ cid });
    
    // 重新加载评论列表
    const res = await getDiscussDetail({ did: discussDetail.value.did });
    commentList.value = res.data.comments || [];
    
    ElMessage.success('删除成功');
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败');
    }
  }
};

// 判断是否可以删除评论
const canDeleteComment = (comment: any) => {
  return userStore.isAuthenticated && 
    (userStore.uid === comment.uid || userStore.uid === discussDetail.value?.uid);
};

onMounted(() => {
  loadDiscussDetail();
});
</script>

<style scoped>
.discuss-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.back-link {
  margin-bottom: 20px;
}

.loading-container, .empty-container {
  padding: 40px 0;
}

.discuss-content-container {
  margin-bottom: 30px;
}

.discuss-header {
  margin-bottom: 20px;
}

.discuss-title {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.discuss-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
  color: #909399;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-name {
  font-weight: bold;
  color: #303133;
}

.publish-time {
  color: #909399;
  font-size: 12px;
}

.discuss-tags {
  display: flex;
  gap: 8px;
  margin-bottom: 20px;
}

.discuss-body {
  line-height: 1.8;
  color: #303133;
  margin-bottom: 20px;
}

.discuss-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

.comment-container {
  border-top: 1px solid #e6e6e6;
  padding-top: 20px;
}

.comment-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #303133;
}

.comment-form {
  margin-bottom: 20px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.login-tip {
  margin-bottom: 20px;
}

.login-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 10px;
}

.comment-list {
  margin-top: 20px;
}

.comment-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.comment-item {
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 15px;
  border: 1px solid #e6e6e6;
  background-color: #f9f9f9;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.commenter-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.commenter-name {
  font-weight: bold;
  color: #303133;
}

.comment-time {
  font-size: 12px;
  color: #909399;
}

.comment-content {
  line-height: 1.6;
  color: #606266;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

:deep(.markdown-body) {
  font-size: 16px;
}

:deep(pre) {
  background-color: #f6f8fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
}

:deep(code) {
  font-family: Consolas, Monaco, 'Andale Mono', monospace;
}
</style> 